const date = new Date();
const years = []
const months = []
const days = []
const bigMonth = [1, 3, 5, 7, 8, 10, 12]
var getYear = date.getFullYear()
var getMonth = date.getMonth()
var getDate = date.getDate()
for (let i = getYear - 20; i <= getYear + 20; i++) {years.push(i);}
for (let i = 1; i <= 12; i++) {months.push(i);}
for (let i = 1; i <= 31; i++) {days.push(i);}
Page({
  data: {
    year: getYear,
    month: getMonth+1,
    day: getDate,

    years: years,
    months: months,
    days: days,
    value: [20, getMonth, getDate-1],

    timeInput: '',
    propDate: false,
  },
  onLoad: function (options) {
  
  },
  closePick() {
    this.setData({
      propDate: false
    })
  },
  openPick () {
    let valueDate = ''
    if(this.data.timeInput){
      const res = this.data.timeInput.split("-")
      const year = res[0].substring(2)
      const newRes = [ year-1, res[1]-1, res[2]-1]
      valueDate = newRes
    }else{
      const year = this.data.year.toString().substring(2)
      valueDate = [year-1 , this.data.month-1 ,this.data.day-1]
    }
    this.setData({
      propDate: true,
      value:valueDate
    })
  },
  clearPick() {
    this.setData({
      value:'',
      timeInput:''
    })
  },
  //判断元素是否在一个数组
  contains(arr, obj) {
    var i = arr.length;
    while (i--) {
      if (arr[i] === obj) {
        return true;
      }
    }
    return false;
  },
  setDays(day) {
    const temp = [];
    for (let i = 1; i <= day; i++) {
      temp.push(i)
    }
    this.setData({
      days: temp,
    })
  },
  //选择滚动器改变触发事件
  bindChange (e) {
    const val = e.detail.value;
    //判断月的天数
    const setYear = this.data.years[val[0]];
    const setMonth = this.data.months[val[1]];
    const setDay = this.data.days[val[2]]
    this.setData({
      year: setYear,
      month: setMonth,
      day: setDay
    })
    if (setMonth === 2) {
      this.setDays((setYear % 4 === 0 && setYear % 100 !== 0) ? 29 : 28)
    } else {
      this.setDays(this.contains(bigMonth, setMonth)? 31 : 30)
    }
    this.setData({
      timeInput: setYear + '-' + setMonth + '-' + setDay
    })
  }
})